﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml;
using ExaminationSys.DataAccess.Entity;
using Ext.Net;
using System.Reflection;
using System.Web.UI;
using System.Security.Cryptography;
using System.Text;

namespace ExaminationSys.Helper
{
    public static class DESHelper
    {
        private static byte[] IV = {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF};
           public static readonly string desKey = System.Configuration.ConfigurationManager.AppSettings["DESKey"];
        public static string Encrypt(string source)
        {
            return Encrypt(desKey, source);
        }

        public static string Decrypt(string decryptStr)
        {
            return Decrypt(desKey, decryptStr);
        }

        public static string Encrypt(string key, string str)
        {
            if (string.IsNullOrEmpty(key)) throw new ArgumentNullException("key");
            if (string.IsNullOrEmpty(str)) throw new ArgumentNullException("str");


            byte[] bKey = Encoding.UTF8.GetBytes(key.Substring(0, 8));
            byte[] bIV = IV;
            byte[] bStr = Encoding.UTF8.GetBytes(str);
            try
            {
                DESCryptoServiceProvider desc = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, desc.CreateEncryptor(bKey, bIV), CryptoStreamMode.Write);
                cStream.Write(bStr, 0, bStr.Length);
                cStream.FlushFinalBlock();
                return Convert.ToBase64String(mStream.ToArray());
            }
            catch
            {
                return string.Empty;
            }
        }

        public static string Decrypt(string key, string decryptStr)
        {
            if (string.IsNullOrEmpty(key)) throw new ArgumentNullException("key");
            if (string.IsNullOrEmpty(decryptStr)) throw new ArgumentNullException("decryptStr");

            try
            {
                byte[] bKey = Encoding.UTF8.GetBytes(key.Substring(0, 8));
                byte[] bIV = IV;
                byte[] bStr = Convert.FromBase64String(decryptStr);
                DESCryptoServiceProvider desc = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, desc.CreateDecryptor(bKey, bIV), CryptoStreamMode.Write);
                cStream.Write(bStr, 0, bStr.Length);
                cStream.FlushFinalBlock();
                return Encoding.UTF8.GetString(mStream.ToArray());
            }
            catch
            {
                return string.Empty;
            }
        }
    }

    public class UIHelpers
    {
        public static StringBuilder BuildLoginBoxHtml(Student student)
        {
            var sb = new StringBuilder();
            if (student == null) return sb;
            sb.Append("<div class=\"box203\">");
            sb.Append("<div class=\"titles\">");
            sb.Append("<img src=\"images/tit_xx.gif\" alt=\"用户信息\" /></div>");
            sb.Append("<div class=\"conts side-login-on\">");
            sb.Append("<p class=\"tit\">");
            sb.AppendFormat("<span class=\"red\">欢迎您！</span><span>{0}</span>同学</p>", student.UserName);
            sb.Append("<ul>");
            sb.Append("<li><a href=\"Profile.aspx\">个人资料</a></li>");
            sb.Append("<li><a href=\"ChangePassword.aspx\">密码修改</a></li>");
            sb.Append("</ul>");
            sb.Append("<div class=\"button\">");
            sb.Append(
                "<a href=\"StudyCenter.aspx\" id=\"btnStudycenter\"><span style=\"border:1px solid #e3e3e3;color:red;padding:3px;margin:18px\">学习中心</span></a>");
            sb.Append(
                "<input class=\"publicbtn btn-logout\" id=\"btnSignOut\" name=\"\" type=\"button\" value=\"退出\" /></div>");
            sb.Append("</div>");
            sb.Append(" <div class=\"box-bbg\"> </div> </div>");
            return sb;
        }
        public static string ReplaceHtmlTag(string htmlstring)
        {
            //删除脚本   
            htmlstring = Regex.Replace(htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
            //删除HTML   
            htmlstring = Regex.Replace(htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"-->", "", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);

            htmlstring = Regex.Replace(htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&(nbsp|#160);", "   ", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
            htmlstring = Regex.Replace(htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);

            htmlstring.Replace("<", "");
            htmlstring.Replace(">", "");
            htmlstring.Replace("\r\n", "");
            htmlstring = HttpContext.Current.Server.HtmlEncode(htmlstring).Trim();

            return htmlstring;
        }



        public static readonly string BasePath = System.Configuration.ConfigurationManager.AppSettings["UploadPath"];

        public static NodeCollection BuildTreeNodes()
        {
            NodeCollection result = new NodeCollection();
 
            Node node = new Node();
            node.Text = "公共信息管理";
            node.IconCls = "icon-lightning";

            Node node2 = new Node();
            //node2.Text = "信息类别";
            string url = "";// "/View/News/NewsTypeList.aspx";
            //node2.NodeID = "e" + Math.Abs(url.ToLower().GetHashCode());
            //node2.Href = url;
            //node2.Leaf = true;
            //node.Children.Add(node2);

            var express = new Node();
            express.Text = "信息快递";
            url = "/View/News/ExpressInfoList.aspx";
            express.NodeID = "e" + Math.Abs(url.ToLower().GetHashCode());
            express.Href = url;
            express.Leaf = true;
            node.Children.Add(express);

            express = new Node();
            express.Text = "帮助";
            url = "/View/News/HelperInfoList.aspx";
            express.NodeID = "e" + Math.Abs(url.ToLower().GetHashCode());
            express.Href = url;
            express.Leaf = true;
            node.Children.Add(express);
            result.Add(node);


            //用户管理
            Node nodeUserManage = new Node();
            nodeUserManage.Text = "用户管理";
            nodeUserManage.IconCls = "icon-lightning";

            var teachNode = new Node();
            teachNode.Text = "教师用户";
            url = "/View/SystemManage/TeacherInfoList.aspx";
            teachNode.NodeID = "e" + Math.Abs(url.ToLower().GetHashCode());
            teachNode.Href = url;
            teachNode.Leaf = true;
            nodeUserManage.Children.Add(teachNode);

            var studentNode = new Node();
            studentNode.Text = "学生用户";
            url = "/View/SystemManage/StudentInfoList.aspx";
            studentNode.NodeID = "e" + Math.Abs(url.ToLower().GetHashCode());
            studentNode.Href = url;
            studentNode.Leaf = true;
            nodeUserManage.Children.Add(studentNode);


            //var passwordNode = new Node();
            //passwordNode.Text = "密码修改";
            //url = "/View/SystemManage/SysUserList2.aspx";
            //passwordNode.NodeID = "e" + Math.Abs(url.ToLower().GetHashCode());
            //passwordNode.Href = url;
            //passwordNode.Leaf = true;
            //nodeUserManage.Children.Add(passwordNode);

            result.Add(nodeUserManage);

            Node sectionManage = new Node();
            sectionManage.Text = "栏目管理";
            sectionManage.IconCls = "icon-lightning";

            var sectionSettingNode = new Node();
            sectionSettingNode.Text = "栏目设置";
            url = "/View/Section/SectionInfoList.aspx";
            sectionSettingNode.NodeID = "e" + Math.Abs(url.ToLower().GetHashCode());
            sectionSettingNode.Href = url;
            sectionSettingNode.Leaf = true;
            sectionManage.Children.Add(sectionSettingNode);

            var sectionDectailNode = new Node();
            sectionDectailNode.Text = "栏目管理";
            url = "/View/Section/SectionDetailList.aspx";
            sectionDectailNode.NodeID = "e" + Math.Abs(url.ToLower().GetHashCode());
            sectionDectailNode.Href = url;
            sectionDectailNode.Leaf = true;
            sectionManage.Children.Add(sectionDectailNode);

            result.Add(sectionManage);


            Node QuestionManage = new Node();
            QuestionManage.Text = "题库管理";
            QuestionManage.IconCls = "icon-lightning";

            var commonQuestionNode = new Node();
            commonQuestionNode.Text = "普通题";
            url = "/View/SystemManage/DBQuestionList.aspx";
            commonQuestionNode.NodeID = "e" + Math.Abs(url.ToLower().GetHashCode());
            commonQuestionNode.Href = url;
            commonQuestionNode.Leaf = true;
            QuestionManage.Children.Add(commonQuestionNode);

            var hardQuestionNode = new Node();
            hardQuestionNode.Text = "大题";
            url = "/View/SystemManage/DBSubjectList.aspx";
            hardQuestionNode.NodeID = "e" + Math.Abs(url.ToLower().GetHashCode());
            hardQuestionNode.Href = url;
            hardQuestionNode.Leaf = true;
            QuestionManage.Children.Add(hardQuestionNode);

            result.Add(QuestionManage);

            
            Node PaperManage = new Node();
            PaperManage.Text = "试卷管理";
            PaperManage.IconCls = "icon-lightning";

            var PaperNode = new Node();
            PaperNode.Text = "试卷管理";
            url = "/View/Paper/PaperInfoList.aspx";
            PaperNode.NodeID = "e" + Math.Abs(url.ToLower().GetHashCode());
            PaperNode.Href = url;
            PaperNode.Leaf = true;
            PaperManage.Children.Add(PaperNode);

            var PaperFeedBackComment = new Node();
            PaperFeedBackComment.Text = "评语管理";
            url = "/View/Paper/PaperFeedBackCommentList.aspx";
            PaperFeedBackComment.NodeID = "e" + Math.Abs(url.ToLower().GetHashCode());
            PaperFeedBackComment.Href = url;
            PaperFeedBackComment.Leaf = true;
            PaperManage.Children.Add(PaperFeedBackComment);

            

            result.Add(PaperManage);

            //Node sysTeamSettingManage = new Node();
            //sysTeamSettingManage.Text = "系统设置";
            //sysTeamSettingManage.IconCls = "icon-lightning";

            //var stageSettingNode = new Node();
            //stageSettingNode.Text = "阶段设置";
            //url = "/View/SystemManage/SysUserList7.aspx";
            //stageSettingNode.NodeID = "e" + Math.Abs(url.ToLower().GetHashCode());
            //stageSettingNode.Href = url;
            //stageSettingNode.Leaf = true;
            //sysTeamSettingManage.Children.Add(stageSettingNode);

           // result.Add(sysTeamSettingManage);

            Node ReportManage = new Node();
            ReportManage.Text = "报表";
            ReportManage.IconCls = "icon-lightning";

            var PaperReport = new Node();
            PaperReport.Text = "试卷统计";
            url = "/View/SystemManage/PaperReport.aspx";
            PaperReport.NodeID = "e" + Math.Abs(url.ToLower().GetHashCode());
            PaperReport.Href = url;
            PaperReport.Leaf = true;
            ReportManage.Children.Add(PaperReport);


            result.Add(ReportManage);


            //node = new Node();
            //node.Text = "B";
            //node.IconCls = "icon-lightning";

            //node2 = new Node();
            //node2.Text = "test";
            //url = "About.aspx"; // PhysicalToVirtual("/Test");
            //node2.Href = url;
            //node2.Leaf = true;
            //node2.NodeID = "e" + Math.Abs(url.ToLower().GetHashCode());
            //node.Children.Add(node2);
            //result.Add(node);

            return result;


        }

        /// <summary>
        /// 设置Entity的属性值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t">Entity对象</param>
        /// <param name="container">容器</param>
        public static void SetEntity<T>(T t, Window container)
        {
            PropertyInfo[] PropertyInfos = t.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);//获得对象的所有public属性

            foreach (var property in PropertyInfos)
            {
                Control ctl = container.FindControl(property.Name);
                object ctlValue = string.Empty;
                if (ctl == null || ctl.GetType() == null)
                {
                    continue;
                }

                switch (ctl.GetType().Name)
                {
                    case "TextField":
                        ctlValue = ((TextField)ctl).Text.Trim();
                        break;
                    case "Checkbox":
                        ctlValue = ((Checkbox)ctl).Checked;
                        break;
                    case "HtmlEditor":
                        ctlValue = ((HtmlEditor)ctl).Value;
                        break;
                    case "DateField ":
                        ctlValue = ((DateField)ctl).SelectedValue;
                        break;
                    case "Label":
                        ctlValue = ((Label)ctl).Text;
                        break;
                    default:
                        break;
                }
                property.SetValue(t, Convert.ChangeType(ctlValue, property.PropertyType), null);
            }
        }

        /// <summary>
        /// 得到Entity的属性值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t">Entity对象</param>
        /// <param name="container">容器</param>
        public static void GetEntity<T>(T t, Window container)
        {
            PropertyInfo[] PropertyInfos = t.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);//获得对象的所有public属性

            foreach (var property in PropertyInfos)
            {
                Control ctl = container.FindControl(property.Name);
                string ctlValue = string.Empty;
                if (ctl == null || ctl.GetType() == null)
                {
                    continue;
                }
                ctlValue = property.GetValue(t, null).ToString();
                switch (ctl.GetType().Name)
                {
  
                    case "TextField":
                        ((TextField)ctl).Text = ctlValue;
                        break;
                    case "Checkbox":
                         ((Checkbox)ctl).Checked = ctlValue == "true" ? true : false;
                        break;
                    case "HtmlEditor":
                        ((HtmlEditor)ctl).Value = ctlValue;
                        break;
                    case "DateField ":
                        ((DateField)ctl).SelectedValue = ctlValue;
                        break;
                    case "Label":
                        ((Label)ctl).Text = ctlValue;
                        break;
                    default:
                        break;
                }
            }
        }

    }
}